package com.ruoyi.system.service.impl;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.springframework.http.ResponseEntity;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import com.ruoyi.system.domain.comment.FileComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.BEFileMapper;
import com.ruoyi.system.domain.BEFile;
import com.ruoyi.system.service.IBEFileService;
import com.ruoyi.system.mapper.BEAnjuanMapper;
import com.ruoyi.system.domain.BEAnjuan;

/**
 * 文件Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-08
 */
@Service
public class BEFileServiceImpl implements IBEFileService 
{
    @Autowired
    private BEFileMapper bEFileMapper;

    private String path="C:\\ruoyi\\uploadPath";
    private String profile = "/profile";
    @Autowired
    private BEAnjuanMapper bEAnjuanMapper;
    /**
     * 查询文件
     * 
     * @param id 文件主键
     * @return 文件
     */
    @Override
    public BEFile selectBEFileById(String id)
    {
        return bEFileMapper.selectBEFileById(id);
    }

    /**
     * 查询文件列表
     * 
     * @param bEFile 文件
     * @return 文件
     */
    @Override
    public List<BEFile> selectBEFileList(BEFile bEFile)
    {
        return bEFileMapper.selectBEFileList(bEFile);
    }

    /**
     * 新增文件
     * 
     * @param bEFile 文件
     * @return 结果
     */
    @Override
    public int insertBEFile(BEFile bEFile)
    {
        return bEFileMapper.insertBEFile(bEFile);
    }

    /**
     * 修改文件
     * 
     * @param bEFile 文件
     * @return 结果
     */
    @Override
    public int updateBEFile(BEFile bEFile)
    {
        return bEFileMapper.updateBEFile(bEFile);
    }

    /**
     * 批量删除文件
     * 
     * @param ids 需要删除的文件主键
     * @return 结果
     */
    @Override
    public int deleteBEFileByIds(String[] ids)
    {
        return bEFileMapper.deleteBEFileByIds(ids);
    }

    /**
     * 删除文件信息
     * 
     * @param id 文件主键
     * @return 结果
     */
    @Override
    public int deleteBEFileById(String id)
    {
        return bEFileMapper.deleteBEFileById(id);
    }

    /**
     * 查询文件注释信息列表
     *
     * @return 文件信息集合
     */
    public List<FileComment> selectBeFileComInfoList(){
        return bEFileMapper.selectBeFileComInfoList();
    }



    /**
     * 获取二进制文件
     *
     * @param id 文件信息主键
     * @return pdf
     */
//    public ResponseEntity<byte[]> getpdf(String id){
//        try {
//            // 从classpath中加载PDF文件
//
//            BEFile beFile = bEFileMapper.selectBEFileById(id);
//            BEAnjuan beAnjuan = bEAnjuanMapper.selectBEAnjuanById(beFile.getEaid());
//            String folderPath = beAnjuan.getPath() + File.separator;
//            String houzhui = "pdf";
//            File folder = new File(folderPath);
//            if(folder.isDirectory()){
//                Map<String,String> fileDetails = new HashMap<>();
//                readFiles(folder,fileDetails);
//                houzhui = fileDetails.get(beFile.getWenJianName());
//            }
//            File localFile = new File(beAnjuan.getPath() + File.separator + beFile.getWenJianName() + "." + houzhui);
//
//            // 将PDF文件内容转换为字节数组
//            byte[] localBytes = Files.readAllBytes(localFile.toPath());
//            return ResponseEntity.ok().header("Content-Type", "application/pdf").body(localBytes);
//        }catch (IOException e) {
//            e.printStackTrace();
//            return ResponseEntity.badRequest().build();
//        }
//    }
    public ResponseEntity<byte[]> getpdf(String id){
        try {
            // 从classpath中加载PDF文件

            BEFile beFile = bEFileMapper.selectBEFileById(id);
            String fullPath = beFile.getFilepath();
            String cleanPath = removePrefix(fullPath, profile);
            File localFile = new File(path + File.separator + cleanPath + File.separator);
            // 将PDF文件内容转换为字节数组
            byte[] localBytes = Files.readAllBytes(localFile.toPath());
            return ResponseEntity.ok().header("Content-Type", "application/pdf").body(localBytes);
        }catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    public static String removePrefix(String original, String prefix) {
        if (original.startsWith(prefix)) {
            // 去除前缀并确保路径仍然以斜杠开始
            return "/" + original.substring(prefix.length() + 1);
        } else {
            // 如果原始路径不以指定前缀开头，则返回原始路径
            return original;
        }
    }

//    //读取文件名称与类型
//    public static void readFiles(File folder, Map<String, String> fileDetails) {
//        File[] files = folder.listFiles(); // 获取文件夹中的所有文件
//        for (File file : files) {
//            if (file.isDirectory()) {
//                readFiles(file, fileDetails); // 递归遍历子文件夹中的文件
//            } else {
//                String fileName = file.getName();
//                String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
//                String nameWithoutExtension = fileName.substring(0, fileName.lastIndexOf("."));
//                fileDetails.put(nameWithoutExtension, fileType); // 将不带类型的文件名称和类型存储到字典中
//            }
//        }
//    }

    /**
     * 获取Type
     *
     * @param id 文件信息主键
     * @return type
     */
//    public String getType(String id){
//        BEFile beFile = bEFileMapper.selectBEFileById(id);
//        BEAnjuan beAnjuan = bEAnjuanMapper.selectBEAnjuanById(beFile.getEaid());
//        String folderPath = beAnjuan.getPath() + File.separator;
//        String houzhui = "pdf";
//        File folder = new File(folderPath);
//        if(folder.isDirectory()){
//            Map<String,String> fileDetails = new HashMap<>();
//            readFiles(folder,fileDetails);
//            houzhui = fileDetails.get(beFile.getWenJianName());
//        }
//        return houzhui;
//    }

    /**
     *
     * 批量下载
     *
     */
//    public ResponseEntity<byte[]> downloadMore(String[] ids){
//        String filePath = "D:\\temporaryFolder";
//        String zipPath = "D:\\fileZip.zip";
//        try{
//            File folder = new File(filePath);
//            if(!folder.exists()){
//                folder.mkdirs();
//            }
//
//            for(String fileId : ids){
//                String id = fileId.replace("++","/");
//                BEFile beFile = bEFileMapper.selectBEFileById(id);
//                BEAnjuan beAnjuan = bEAnjuanMapper.selectBEAnjuanById(beFile.getEaid());
//                String folderPath = beAnjuan.getPath() + File.separator;
//                String houzhui = "pdf";
//                File VolumeFolder = new File(folderPath);
//                if(VolumeFolder.isDirectory()){
//                    Map<String,String> fileDetails = new HashMap<>();
//                    readFiles(VolumeFolder,fileDetails);
//                    houzhui = fileDetails.get(beFile.getWenJianName());
//                }
//                File oldFile = new File(beAnjuan.getPath() + File.separator + beFile.getWenJianName() + "." + houzhui);
//                String targetPath = "D:\\temporaryFolder\\" + beFile.getWenJianName() + "." + houzhui;
//                File newFile = new File(targetPath);
//                Files.copy(oldFile.toPath(),newFile.toPath());
//            }
//            zipFolder(filePath,zipPath);
//            byte[] zipFileData = readZipFile(zipPath);
//
//            File folderToDelete = new File(filePath);
//            deleteFolderAndContents(folderToDelete);
//            File zipFileToDelete = new File(zipPath);
//            deleteFile(zipFileToDelete);
//            return ResponseEntity.ok().header("Content-Type","application/zip").body(zipFileData);
//        }catch (IOException e){
//            e.printStackTrace();
//            return ResponseEntity.badRequest().build();
//        }
//    }
    public ResponseEntity<byte[]> downloadMore(String[] ids){
        String filePath = "D:\\temporaryFolder";
        String zipPath = "D:\\fileZip.zip";
        try{
            File folder = new File(filePath);
            if(!folder.exists()){
                folder.mkdirs();
            }

            for(String fileId : ids){
                String id = fileId.replace("++","/");
                BEFile beFile = bEFileMapper.selectBEFileById(id);
                String fullPath = beFile.getFilepath();
                String cleanPath = removePrefix(fullPath, profile);
                File oldFile = new File(path + File.separator + cleanPath + File.separator);
                String targetPath = "D:\\temporaryFolder\\" + beFile.getWenJianName() + "." + beFile.getFiletype();
                File newFile = new File(targetPath);
                Files.copy(oldFile.toPath(),newFile.toPath());
            }
            zipFolder(filePath,zipPath);
            byte[] zipFileData = readZipFile(zipPath);

            File folderToDelete = new File(filePath);
            deleteFolderAndContents(folderToDelete);
            File zipFileToDelete = new File(zipPath);
            deleteFile(zipFileToDelete);
            return ResponseEntity.ok().header("Content-Type","application/zip").body(zipFileData);
        }catch (IOException e){
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    public void zipFolder(String folderPath, String zipFileName) throws IOException {
        File folder = new File(folderPath);

        if (folder.exists() && folder.isDirectory()) {
            try (FileOutputStream fos = new FileOutputStream(zipFileName);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {
                for (File file : folder.listFiles()) {
                    if (file.isFile()) {
                        ZipEntry zipEntry = new ZipEntry(file.getName());
                        zos.putNextEntry(zipEntry);

                        try (FileInputStream fis = new FileInputStream(file)) {
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = fis.read(buffer)) > 0) {
                                zos.write(buffer, 0, length);
                            }
                        }

                        zos.closeEntry();
                    }
                }
            }
        }
    }

    private byte[] readZipFile(String zipFileName) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream fis = new FileInputStream(zipFileName);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        fis.close();
        return baos.toByteArray();
    }

    private static boolean deleteFolderAndContents(File folder) {
        if (folder.exists()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        if (!deleteFolderAndContents(file)) {
                            return false;
                        }
                    } else {
                        if (!deleteFile(file)) {
                            return false;
                        }
                    }
                }
            }
            return folder.delete();
        }
        return false;
    }

    private static boolean deleteFile(File file) {
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }



}
